<!-- src/components/BucketContents/ObjectTable.vue (最终版 - 统一交互) -->
<template>
    <el-table ref="tableRef" :data="tableData" style="width: 100%" @select="onRowSelect"
        @selection-change="onSelectionChange" @sort-change="onTableSortChange" row-key="unique_key"
        :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="55" />

        <!-- 文件名列 (保持不变) -->
        <el-table-column label="文件名" sortable="custom" prop="name" min-width="300">
            <template #default="scope">
                <!-- 只在“隐藏版本”模式下才显示文件夹和普通文件 -->
                <div class="file-name-cell" v-if="!showVersions">
                    <el-icon :size="20">
                        <component :is="getFileIcon(scope.row)" />
                    </el-icon>
                    <a v-if="scope.row.type === 'folder'" @click.prevent="$emit('navigate', scope.row.name)" href="#"
                        class="folder-link">
                        {{ getBaseName(scope.row.name) }}
                    </a>
                    <span v-else>{{ getBaseName(scope.row.name) }}</span>
                </div>
                <!-- 在“显示版本”模式下的特殊渲染 -->
                <div class="file-name-cell" v-else>
                    <template v-if="scope.row.is_header_row">
                        <span class="header-row-name">{{ getBaseName(scope.row.name) }}</span>
                    </template>
                    <template v-else-if="scope.row.type === 'folder'">
                        <el-icon :size="20">
                            <Folder />
                        </el-icon>
                        <a @click.prevent="$emit('navigate', scope.row.name)" href="#" class="folder-link">
                            {{ getBaseName(scope.row.name) }}
                        </a>
                    </template>
                    <template v-else>
                        <el-icon :size="20">
                            <component :is="getFileIcon(scope.row)" />
                        </el-icon>
                        <div class="version-info-cell">
                            <span>{{ formatDateTime(scope.row.date_modified) }}</span>
                            <el-tag v-if="scope.row.is_latest" size="small" type="success" effect="plain">最新版本</el-tag>
                            <el-tag v-else-if="scope.row.type === 'file'" size="small" type="info"
                                effect="plain">历史版本</el-tag>
                            <el-tag v-if="scope.row.type === 'delete_marker'" size="small" type="danger"
                                effect="plain">删除标记</el-tag>
                        </div>
                    </template>
                </div>
            </template>
        </el-table-column>

        <el-table-column prop="size" label="文件大小" width="150" align="right" sortable="custom">
            <template #default="{ row }">
                <span v-if="row.type === 'folder'"></span>
                <span v-else>{{ row.size }}</span>
            </template>
        </el-table-column>

        <el-table-column v-if="!showVersions" prop="date_modified" label="更新时间" width="200" sortable="custom">
            <template #default="scope">
                <span v-if="!showVersions || scope.row.is_header_row || scope.row.type === 'folder'">
                    {{ formatDateTime(scope.row.date_modified) }}
                </span>
            </template>
        </el-table-column>

        <!-- ======================= 【核心修改】操作列 - 统一交互逻辑 ======================= -->
        <el-table-column width="200" fixed="right">
            <template #header>
                <div class="action-header">操作</div>
            </template>
            <template #default="scope">
                <div class="action-buttons" v-if="!scope.row.is_header_row">
                    <!-- 恢复按钮 (只在显示版本模式下特定条件下显示) -->
                    <el-button
                        v-if="showVersions && (scope.row.type === 'delete_marker' || (scope.row.type === 'file' && !scope.row.is_latest))"
                        link type="primary" :loading="restoringVersionId === scope.row.version_id"
                        :disabled="!!restoringVersionId" @click="handleRestore(scope.row)">
                        {{ restoringVersionId === scope.row.version_id ? '恢复中...' : '恢复' }}
                    </el-button>

                    <!-- 详情按钮 (两种模式下都显示，但对文件夹禁用) -->
                    <el-button link type="primary" @click="$emit('detail', scope.row)"
                        :disabled="scope.row.type !== 'file'">详情</el-button>

                    <!-- 下载按钮 (只在隐藏版本模式下显示) -->
                    <el-button v-if="!showVersions" link type="primary"
                        @click="handleDownload(scope.row)">下载</el-button>

                    <!-- “更多” 下拉菜单 -->
                    <el-dropdown trigger="click" @command="(cmd) => handleMoreCommand(scope.row, cmd)">
                        <el-button link type="primary" class="more-actions-btn">
                            更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <!-- v-if 用于条件渲染菜单项 -->
                                <el-dropdown-item v-if="!showVersions" command="setMetadata"
                                    :disabled="scope.row.type !== 'file'">设置元数据</el-dropdown-item>
                                <el-dropdown-item command="delete" :divided="!showVersions">
                                    {{ showVersions ? '彻底删除' : '删除' }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </template>
        </el-table-column>
        <!-- ======================================================================================= -->
    </el-table>

    <!-- 弹窗组件 (保持不变) -->
    <SetObjectMetadataDrawer v-if="metadataDrawerVisible" v-model="metadataDrawerVisible" :bucket-name="bucketName"
        :object-key="selectedItemKey" mode="single" @success="handleMetadataUpdateSuccess" />
</template>

<script setup>
// script 部分的代码完全不需要修改，逻辑是通用的
import { ref } from 'vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';
import { Folder, Document, Picture as PictureIcon, Headset, VideoPlay, ArrowDown } from '@element-plus/icons-vue';
import { getBaseName, formatDateTime } from '@/utils/formatters.js';
import { secureDownloadItem } from '@/utils/downloadHelper';
import SetObjectMetadataDrawer from '@/components/SetObjectMetadataDrawer.vue';

const props = defineProps({
    tableData: { type: Array, required: true },
    isVersioningEnabled: { type: Boolean, default: false },
    showVersions: { type: Boolean, default: false },
    bucketName: { type: String, required: true },
});
const emit = defineEmits(['selection-change', 'navigate', 'detail', 'delete', 'restore', 'action-completed', 'row-selection-change', 'refresh', 'sort-change']);
const tableRef = ref(null);
const restoringVersionId = ref(null);

const metadataDrawerVisible = ref(false);
const selectedItemKey = ref('');

defineExpose({
    toggleAllSelection: () => tableRef.value?.toggleAllSelection(),
    clearSelection: () => tableRef.value?.clearSelection(),
    getTableRef: () => tableRef.value,
});

const onRowSelect = (selection, row) => {
    emit('row-selection-change', selection, row);
};
const onSelectionChange = (selection) => emit('selection-change', selection);

const onTableSortChange = (payload) => {
    // 它的唯一职责就是把事件转发出去
    emit('sort-change', payload);
};

const tableRowClassName = ({ row }) => {
    if (row.is_header_row) return 'header-row';
    if (!row.is_header_row && row.type !== 'folder') return 'version-row';
    return '';
};

const getFileIcon = (item) => {
    if (!item || !item.name) return Document;
    if (item.type === 'folder') return Folder;
    if (item.type === 'delete_marker' || item.type === 'file') {
        const extension = item.name.split('.').pop().toLowerCase();
        if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(extension)) return PictureIcon;
        if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'].includes(extension)) return VideoPlay;
        if (['mp3', 'wav', 'ogg', 'flac'].includes(extension)) return Headset;
    }
    return Document;
};

const handleDownload = (row) => {
    secureDownloadItem(props.bucketName, row);
};

const handleRestore = async (item) => {
    if (restoringVersionId.value) return;
    try {
        restoringVersionId.value = item.version_id;
        await apiClient.post(`/api/v1/buckets/${props.bucketName}/objects/restore-version`, {
            key: item.name,
            versionId: item.version_id,
        });
        ElMessage.success('版本已成功恢复！');
        emit('action-completed');
    } catch (error) {
        console.error(`恢复操作失败:`, error);
        const errorMessage = error.response?.data?.error || '操作失败，请重试';
        ElMessage.error(errorMessage);
    } finally {
        restoringVersionId.value = null;
    }
};

const handleMoreCommand = (item, command) => {
    selectedItemKey.value = item.name;
    switch (command) {
        case 'setMetadata':
            metadataDrawerVisible.value = true;
            break;
        case 'delete':
            // 冒泡删除事件给父组件，父组件会根据showVersions状态决定是普通删除还是彻底删除
            emit('delete', [item]);
            break;
    }
};

const handleMetadataUpdateSuccess = () => {
    emit('refresh');
};
</script>

<style scoped>
.action-buttons {
    display: flex;
    justify-content: flex-end;
    /* 靠右对齐 */
    align-items: center;
    /* 垂直居中对齐 */
    width: 100%;
    gap: 8px;
    /* 【修改2】为所有按钮之间添加8px的间距 */
}

.action-header {
    text-align: right;
    padding-right: 70px;
    /* 添加右内边距，将文字从边缘拉回 */
}

/* 样式部分保持不变 */
.file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.folder-link {
    cursor: pointer;
    color: var(--el-color-primary);
    text-decoration: none;
}

.folder-link:hover {
    text-decoration: underline;
}

.version-info-cell {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #606266;
}

.el-table .header-row {
    font-weight: 500;
    background: #fff !important;
}

.el-table .header-row .cell {
    padding-left: 10px !important;
}

.el-table .version-row {
    background-color: #fafafa !important;
}

.el-table .version-row .cell {
    padding-left: 34px !important;
}

.header-row-name {
    font-weight: bold;
}

.more-actions-btn {
    margin-left: 8px;
}
</style>